//
//  AddEndTimeToTranscript.swift
//  
//
//  Created by System on 2024/11/11.
//

import Fluent
import Vapor

struct AddEndTimeToTranscriptMigration: AsyncMigration {
    var name: String { "AddEndTimeToTranscriptMigration" }
    
    func prepare(on database: any Database) async throws {
        // Add the endTime field if it doesn't exist
        try await database.schema(Transcript.schema)
            .field(Transcript.FieldKeys.endTime, .double, .required)
            .update()
        
        // Now populate the endTime field for existing records
        // We'll set endTime to the startTime of the next transcript with the same audioID,
        // or to the audio duration if it's the last transcript
        
        // Get all transcripts ordered by audioID and startTime
        let transcripts = try await Transcript.query(on: database)
            .sort(\.$audio.$id)
            .sort(\.$startTime)
            .with(\.$audio)
            .all()
        
        // Group transcripts by audioID
        let transcriptsByAudio = Dictionary(grouping: transcripts) { $0.$audio.id }
        
        // Process each audio's transcripts
        for (_, audioTranscripts) in transcriptsByAudio {
            let sortedTranscripts = audioTranscripts.sorted { $0.startTime < $1.startTime }
            
            // Get the audio duration (default to a large value if not available)
            let audioDuration = sortedTranscripts.first?.audio.duration ?? 3600
            
            for i in 0..<sortedTranscripts.count {
                let transcript = sortedTranscripts[i]
                
                if i < sortedTranscripts.count - 1 {
                    // Not the last transcript, use the next transcript's startTime
                    transcript.endTime = sortedTranscripts[i + 1].startTime
                } else {
                    // Last transcript, use the audio duration
                    transcript.endTime = audioDuration
                }
                
                try await transcript.save(on: database)
            }
        }
    }
    
    func revert(on database: any Database) async throws {
        // 由于字段现在是必填的，回滚将无法删除该字段
        // 我们可以将其改为可空，而不是删除
        try await database.schema(Transcript.schema)
            .updateField(Transcript.FieldKeys.endTime, .double)
            .update()
    }
} 